package com.ndood.agent.core.security;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Maps;
import com.ndood.agent.dao.system.StaffDao;
import com.ndood.agent.dao.system.extend.ExtendPermDao;
import com.ndood.agent.dao.system.extend.ExtendRoleDao;
import com.ndood.agent.dao.system.extend.ExtendStaffDao;
import com.ndood.agent.pojo.system.PermPo;
import com.ndood.agent.pojo.system.RolePo;
import com.ndood.agent.pojo.system.StaffPo;
import com.ndood.agent.pojo.system.dto.StaffDto;
import com.ndood.common.base.util.RegexUtils;

/**
 * 自定义UserDetailsService
 * @author ndood
 */
@Transactional
@Component
public class AgentUserDetailsService implements UserDetailsService {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private ExtendStaffDao extendStaffDao;
	
	@Autowired
	private StaffDao staffDao;
	
	@Autowired
	private ExtendRoleDao extendRoleDao;
	
	@Autowired
	private ExtendPermDao extendPermDao;

	/**
	 * 根据username获取用户信息
	 */
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		
		logger.debug("Step1: 进行登录，表单登录用户名:" + username);

		StaffPo staff = null;
		if (RegexUtils.checkEmail(username)) {
			// 查看是否存在未激活邮箱
			staff = extendStaffDao.extendFindByEmailAndStatus(username, 1);
			
		} else if (RegexUtils.checkMobile(username)) {
			staff = extendStaffDao.extendFindByMobileAndStatus(username, 1);
			
		} else {
			// 适用于rememeberMe的调用
			try {
				staff = staffDao.selectByPrimaryKey(Integer.parseInt(username));
			} catch (Exception e) {
				throw new UsernameNotFoundException("无效的账号!");
			}
			
		}

		if (staff == null) {
			throw new UsernameNotFoundException("用户不存在，或已冻结!");
		}

		logger.debug("Step2: 为登录用户设置权限");
		return buildUserAuthorities(staff);
		
	}

	/**
	 * 创建用户，并给用户分配角色
	 */
	private UserDetails buildUserAuthorities(StaffPo staff) {
		StaffDto dto = new StaffDto();
		dto.setAgentId(staff.getAgentId());
		dto.setCreateTime(staff.getCreateTime());
		dto.setEmail(staff.getEmail());
		dto.setHeadImgUrl(staff.getHeadImgUrl());
		dto.setId(staff.getId());
		dto.setLastLoginIp(staff.getLastLoginIp());
		dto.setLastLoginTime(staff.getLastLoginTime());
		dto.setMobile(staff.getMobile());
		dto.setNickName(staff.getNickName());
		dto.setPassword(staff.getPassword());
		dto.setStatus(staff.getStatus());
		dto.setTradePassword(staff.getTradePassword());
		dto.setUpdateTime(staff.getUpdateTime());
		
		Map<String, GrantedAuthority> urlMap = Maps.newHashMap();
		// 将权限url信息加入到urls
		List<RolePo> roles = extendRoleDao.findByStaffId(staff.getId());
		if (roles != null) {
			for (RolePo role : roles) {
				List<PermPo> perms = extendPermDao.findByRoleId(role.getId());
				for (PermPo permPo : perms) {
					String url = permPo.getUrl();
					if (StringUtils.isEmpty(url)) {
						continue;
					}
					url = url.trim();
					urlMap.put(url, new SimpleGrantedAuthority(url));
				}
			}
		}
		dto.getUrlMap().putAll(urlMap);
		return dto;
		
	}
}
